package com.zlfund.cat.zjgsmk.util.timetask;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by chenj
 * Created on 2017/8/15
 */

public class TimerService {
    private Timer mTimer;
    private long mTotalTime;
    private boolean mIsRunning;
    private TimerTask mTask;

    public TimerService(){
    }

    public void timeSchedule(final Runnable r, final long period){
        timeSchedule(r,period,0);
    }

    public void timeSchedule(final Runnable r, final long period,long delay){
        if (mIsRunning) return;
        mIsRunning = true;
        mTask = new TimerTask() {
            @Override
            public void run() {
                r.run();
                mTotalTime += period;
            }
        };
        mTimer = new Timer();
        mTimer.scheduleAtFixedRate(mTask,delay,period);
    }

    public void cancel(){
        if (mTask != null){
            mTask.cancel();
            mTask = null;
        }
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
        mIsRunning = false;
    }

    public long getTotalTime() {
        return mTotalTime;
    }

    public boolean isRunning(){
        return mIsRunning;
    }
}
